<template>
  <div class="guild-activity-participant-manage">
    <h2>公会活动参与者管理</h2>

    <!-- 操作按钮和搜索框 -->
    <div style="margin-bottom: 15px; display: flex; flex-wrap: wrap; gap: 10px;">
      <el-button type="primary" @click="showCreateDialog">添加参与者</el-button>
      <el-button @click="fetchAllParticipants">查询所有参与者</el-button>

      <div style="display: flex; align-items: center; margin-left: auto;">
        <el-input
            v-model="searchActivityId"
            placeholder="按活动ID筛选"
            style="width: 200px; margin-right: 10px;"
            @keyup.enter="fetchParticipantsByActivityId"
        />
        <el-input
            v-model="searchPlayerId"
            placeholder="按玩家ID筛选"
            style="width: 200px;"
            @keyup.enter="fetchParticipantsByPlayerId"
        />
      </div>
    </div>

    <!-- 参与者表格 -->
    <el-table :data="participants" style="width: 100%" border stripe>
      <el-table-column prop="id" label="参与者ID" align="center" width="100"></el-table-column>
      <el-table-column prop="activityId" label="活动ID" align="center" width="120"></el-table-column>
      <el-table-column prop="playerId" label="玩家ID" align="center" width="120"></el-table-column>
      <el-table-column label="操作" align="center" width="200">
        <template #default="scope">
          <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加参与者对话框 -->
    <el-dialog title="添加活动参与者" v-model="dialogVisible" width="30%">
      <el-form :model="participantForm" :rules="rules" label-width="100px">
        <el-form-item label="活动ID" prop="activityId">
          <el-input v-model="participantForm.activityId" placeholder="请输入活动ID"></el-input>
        </el-form-item>
        <el-form-item label="玩家ID" prop="playerId">
          <el-input v-model="participantForm.playerId" placeholder="请输入玩家ID"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
// 确保request.js路径正确
import request from "@/utils/request";

// 参与者数据
const participants = ref([]);
const loading = ref(false);
const searchActivityId = ref('');
const searchPlayerId = ref('');

// 对话框状态
const dialogVisible = ref(false);

// 表单数据
const participantForm = ref({
  id: null,
  activityId: '',
  playerId: ''
});

// 表单验证规则
const rules = {
  activityId: [{ required: true, message: '请输入活动ID', trigger: 'blur' }],
  playerId: [{ required: true, message: '请输入玩家ID', trigger: 'blur' }]
};

// 获取所有参与者
const fetchAllParticipants = async () => {
  try {
    loading.value = true;
    const response = await request.get('/activity/participants/all');
    if (response.data && Array.isArray(response.data)) {
      participants.value = response.data;
    } else {
      participants.value = [];
    }
    ElMessage.success('获取所有参与者成功');
  } catch (error) {
    console.error('获取所有参与者失败:', error);
    ElMessage.error('获取所有参与者失败: ' + (error.response?.data?.message || error.message));
  } finally {
    loading.value = false;
  }
};

// 根据活动ID获取参与者
const fetchParticipantsByActivityId = async () => {
  const activityId = searchActivityId.value.trim();
  if (!activityId) {
    ElMessage.warning('请输入活动ID');
    return;
  }
  try {
    loading.value = true;
    const response = await request.get(`/activity/${activityId}/participants`);
    if (response.data && Array.isArray(response.data)) {
      participants.value = response.data;
    } else {
      participants.value = [];
    }
    ElMessage.success(`获取活动ID为 ${activityId} 的参与者成功`);
  } catch (error) {
    console.error('获取参与者列表失败:', error);
    ElMessage.error('获取参与者列表失败: ' + (error.response?.data?.message || error.message));
  } finally {
    loading.value = false;
  }
};

// 根据玩家ID获取参与者
const fetchParticipantsByPlayerId = async () => {
  const playerId = searchPlayerId.value.trim();
  if (!playerId) {
    ElMessage.warning('请输入玩家ID');
    return;
  }
  try {
    loading.value = true;
    const response = await request.get(`/activity/participant/player/${playerId}`);
    if (response.data && Array.isArray(response.data)) {
      participants.value = response.data;
    } else {
      participants.value = [];
    }
    ElMessage.success(`获取玩家ID为 ${playerId} 的参与者成功`);
  } catch (error) {
    console.error('获取参与者列表失败:', error);
    ElMessage.error('获取参与者列表失败: ' + (error.response?.data?.message || error.message));
  } finally {
    loading.value = false;
  }
};

// 显示创建对话框
const showCreateDialog = () => {
  dialogVisible.value = true;
  participantForm.value = {
    id: null,
    activityId: '',
    playerId: ''
  };
};

// 提交添加参与者表单
const submitForm = async () => {
  try {
    // 表单验证
    for (const prop in rules) {
      if (rules.hasOwnProperty(prop) && !participantForm.value[prop]) {
        throw new Error(`${rules[prop][0].message}`);
      }
    }

    const response = await request.post('/activity/participant', participantForm.value);
    if (response.code === 200) {
      ElMessage.success('添加参与者成功');
      dialogVisible.value = false;
      // 刷新参与者列表
      await fetchAllParticipants();
    } else {
      ElMessage.error(response.message || '添加参与者失败');
    }
  } catch (error) {
    console.error('添加参与者出错:', error);
    ElMessage.error(error.message || '网络请求失败，请检查控制台日志');
  }
};

// 删除参与者
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该参与者吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const response = await request.delete(`/activity/participant/${id}`);
    if (response.code === 200) {
      ElMessage.success('删除参与者成功');
      // 刷新参与者列表
      await fetchAllParticipants();
    } else {
      ElMessage.error(response.message || '删除参与者失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除参与者出错，请检查控制台日志');
    }
  }
};

onMounted(() => {
  fetchAllParticipants();
});
</script>

<style scoped>
.guild-activity-participant-manage {
  padding: 20px;
}
</style>